package com.ct.boot.launch.dao;

import com.ct.boot.launch.dao.testdb.Article;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Auther: Charles chen
 * @Date: 2020/7/15 16:12
 * @Description:
 */
@Repository
public class ArticleJDBCDAO {
    @Resource
    private JdbcTemplate primaryJdbcTemplate;

    public boolean save(Article article,JdbcTemplate jdbcTemplate){
        if (jdbcTemplate==null){
            jdbcTemplate=primaryJdbcTemplate;
        }
        int update = jdbcTemplate.update("INSERT into article(author,title,content,create_time)values (?,?,?,?)",
                article.getAuthor(),
                article.getTitle(),
                article.getContent(),
                new Date()
        );
        if (update!=0){
            return true;
        }
        return false;
    }
    public boolean updateArticle(Article article,JdbcTemplate jdbcTemplate){
        if (jdbcTemplate==null){
            jdbcTemplate=primaryJdbcTemplate;
        }
        Long id = article.getId();
        int update = jdbcTemplate.update("update article set title=?,author=?,content=? WHERE id=?", article.getTitle(), article.getAuthor(), article.getContent(), id);
        return update==1 ?true : false;
    }
    public void deleteById(Long id,JdbcTemplate jdbcTemplate){
        if (jdbcTemplate==null){
            jdbcTemplate=primaryJdbcTemplate;
        }
        jdbcTemplate.update("DELETE FROM article WHERE id=?",id);
    }

    public Article findById(Long id,JdbcTemplate jdbcTemplate){
        if (jdbcTemplate==null){
            jdbcTemplate=primaryJdbcTemplate;
        }
        //自动映射成Article的字段
        return jdbcTemplate.queryForObject("select * from article where id=?",new Object[]{id},new BeanPropertyRowMapper<>(Article.class));
    }
    public List<Article> findAll(JdbcTemplate jdbcTemplate){
        if (jdbcTemplate==null){
            jdbcTemplate=primaryJdbcTemplate;
        }
        return (List<Article>) jdbcTemplate.query("select * from article",new BeanPropertyRowMapper<>(Article.class));
    }


}
